<!-- 头部 -->
<template>
  <div class="leftTopBox-map">
    <div class="boxline">
      <div class="flex justify-between">
        <h2 class="titleText u-m-b-10">学校设备当日在线分布</h2>
        <p style="color:#fff;font-size:16px;">当前在线总数：{{ totalNum }}</p>
      </div>
      <!-- 地图 -->
      <div ref="campusMap" class="location-page" v-loading="loading"
           element-loading-text="地图加载中..."
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)"></div>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import positionImg from '@/assets/img/position2.png'

export default {
  name: 'leftTopBox',
  props: {
    location: {
      default: () => {
        return [116.407387, 39.904179]
      }
    },
    schooleId: {
      type: [String, Number],
      default: () => {
        return 0
      }
    }
  },
  data() {
    return {
      positionImg,
      totalNum: 0,
      loading: true,
      map: null
    };
  },
  mounted() {
    this.loading = true
    this.getData()
  },
  watch: {
    location(val) {
      const interval = setInterval(() => {
        if (this.map) {
          this.map.setCenter(val)
          clearInterval(interval)
        }
      }, 100)
    }
  },
  methods: {
    getData() {
      this.$http.get('/data_center/getTodayDeviceDistribution', {
        params: {schoole_id: this.schooleId}
      }).then(({data}) => {
        this.totalNum = data.data.total
        // this.initMap(data.data.total ? [data.data.list[0].lng, data.data.list[0].lat] : [116.407387, 39.904179], data.data.list)
        this.initMap(this.location, data.data.list)
      });
    },
    initMap(center, markers) {
      AMapLoader.load({
        key: 'a8495fcc75776a9eb1a4f3e907f0b84e', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      }).then(AMap => {
        this.map = new AMap.Map(this.$refs.campusMap, {
          mapStyle: 'amap://styles/darkblue',
          zoom: 14,
          disableDoubleClickZoom: false,
          center: center
        });
        this.map.setFitView()
        if (markers.length) {
          const icon = new AMap.Icon({
            size: new AMap.Size(25, 34),
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
            imageSize: new AMap.Size(25, 34)
          });
          markers.map(markerVal => {
            const marker = new AMap.Marker({
              position: new AMap.LngLat(markerVal.lng, markerVal.lat),
              icon: icon
            })
            this.map.add(marker)
          })
        }
        setTimeout(() => {
          this.loading = false
        }, 100)
      })
    }
  }
};
</script>
<style lang="scss" scoped>
.leftTopBox-map {
  width: 100%;
  height: 100%;

  .boxline,
  .location-page,
  .location-map {
    height: 100%;
  }
}
</style>
